package response

import (
	"gitee.com/lstack_light/light-utils/common/errorCode"
	"net/http"
)

const success = "success"

// Response Uniformly encapsulated response body
type Response struct {
	errorCode.ErrorCode
	Data interface{} `json:"data"`
}

// List Generic array structure
type List struct {
	Total int64         `json:"total"`
	Items []interface{} `json:"items"`
}

// Succeed
/*

@author KangXu

@description In response to success

@return Returns the uniformly encapsulated success response body
*/
func Succeed() Response {
	return Response{
		ErrorCode: errorCode.ErrorCode{
			Code:    http.StatusOK,
			Message: success,
		},
		Data: nil,
	}
}

// SucceedData
/*

@author KangXu

@description Successful response (single object can be returned)

@param data is the object that needs to be returned

@param errs is a possible error

@return Returns a unified encapsulated success response body (carrying a single object)
*/
func SucceedData(data interface{}, errs ...error) Response {
	if 0 < len(errs) {
		if nil != errs[0] {
			return Response{
				ErrorCode: errorCode.ErrorCode{
					Code:    http.StatusInternalServerError,
					Message: errs[0].Error(),
				},
				Data: nil,
			}
		}
	}
	response := Response{
		ErrorCode: errorCode.ErrorCode{
			Code:    http.StatusOK,
			Message: success,
		},
		Data: data,
	}
	return response
}

// SucceedList
/*

@author KangXu

@description Successful response (can return an array object)

@param list is the array to be returned

@param errs is a possible error

@return Returns a unified encapsulated success response body (carrying an array object)
*/
func SucceedList(list List, errs ...error) Response {
	if 0 < len(errs) {
		if nil != errs[0] {
			return Response{
				ErrorCode: errorCode.ErrorCode{
					Code:    http.StatusInternalServerError,
					Message: errs[0].Error(),
				},
				Data: nil,
			}
		}
	}
	response := Response{
		ErrorCode: errorCode.ErrorCode{
			Code:    http.StatusOK,
			Message: success,
		},
		Data: list,
	}
	return response
}

// CustomizeError 设置自定义错误
func CustomizeError(err errorCode.ErrorCode, message ...string) Response {
	msg := err.Message
	if len(message) > 0 {
		msg = message[0]
	}
	response := Response{
		ErrorCode: errorCode.ErrorCode{
			Code:    err.Code,
			Message: msg,
		},
		Data: nil,
	}
	return response
}
